﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace JX.Infrastructure.Common
{
    /// <summary>
    /// 内部异步方法帮助类
    /// </summary>
    internal static class InternalAsyncHelper
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="actualReturnValue"></param>
        /// <param name="finalAction"></param>
        /// <returns></returns>
        public static async Task AwaitTaskWithPostActionAndFinally(Task actualReturnValue, Action<Exception> finalAction)
        {
            Exception exception = null;

            try
            {
                await actualReturnValue;
            }
            catch (Exception ex)
            {
                exception = ex;
            }
            finally
            {
                finalAction(exception);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="actualReturnValue"></param>
        /// <param name="postAction"></param>
        /// <param name="finalAction"></param>
        /// <returns></returns>
        public static async Task<T> AwaitTaskWithPostActionAndFinallyAndGetResult<T>(Task<T> actualReturnValue, Func<Task> postAction, Action<Exception> finalAction)
        {
            Exception exception = null;

            try
            {
                var result = await actualReturnValue;
                await postAction();
                return result;
            }
            catch (Exception ex)
            {
                exception = ex;
                throw;
            }
            finally
            {
                finalAction(exception);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="taskReturnType"></param>
        /// <param name="actualReturnValue"></param>
        /// <param name="finalAction"></param>
        /// <returns></returns>
        public static object CallAwaitTaskWithPostActionAndFinallyAndGetResult(Type taskReturnType, object actualReturnValue, Action<Exception> finalAction)
        {
            MethodInfo methodInfo = typeof(InternalAsyncHelper)
                .GetMethod("AwaitTaskWithPostActionAndFinallyAndGetResult", BindingFlags.Public | BindingFlags.Static);
            methodInfo = methodInfo.MakeGenericMethod(taskReturnType);
            object[] postedParams = new object[] { actualReturnValue, finalAction };
            return methodInfo.Invoke(null, postedParams);
        }
    }
}
